from fastapi import APIRouter, Header, HTTPException
from models.m import Novel
from tool.jwt_utils import verify_token

writer_router = APIRouter()


@writer_router.get("/novels", summary="获取当前作者的全部作品（私有）", tags=["小说"])
async def get_my_novels_private(authorization: str | None = Header(None)):
    try:
        if not authorization or not authorization.lower().startswith("bearer "):
            raise HTTPException(status_code=401, detail="未授权：缺少Bearer Token")

        token = authorization.split(" ", 1)[1].strip()
        payload = verify_token(token)
        if not payload or not payload.get("user_id"):
            raise HTTPException(status_code=401, detail="无效或过期的Token")

        user_id = payload["user_id"]
        novels = await Novel.filter(user_id=user_id).order_by("-updated_at").prefetch_related("category")

        items = []
        for n in novels:
            items.append({
                "id": n.id,
                "title": n.title,
                "category_name": n.category.name if n.category_id else "",
                "status": int(n.status),
                "audit_status": int(n.audit_status),
                "word_count": n.word_count,
                "view_count": n.view_count,
                "collect_count": n.collect_count,
                "is_featured": n.is_featured,
                "updated_at": str(n.updated_at) if n.updated_at else None,
            })

        return {"code": 200, "message": "获取成功", "data": {"list": items, "total": len(items)}}

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取作者作品失败: {str(e)}")






